package com.sisgh.jefdv1.util;

import com.sisgh.jefdv1.exception.common.ClosedException;

import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 负责关闭连接
 */
public class CloseUtils {
    /**
     * 关闭实现 Closeable 的实例
     * @param closes
     * @throws ClosedException
     */
    public static void close(final Closeable... closes) throws ClosedException {
        List<String> errors = new ArrayList<>();
        boolean errorOccurred = false;
        for (final Closeable c : closes) {
            try {
                if (c != null) {
                    c.close();
                }
            } catch (IOException e) {
                errors.add(e.getMessage());
                errorOccurred = true;
            }
        }
        if (errorOccurred) {
            throw new ClosedException(String.join("\n", errors));
        }
    }

    /**
     * 关闭实现 AutoCloseable 的实例
     * @param closes
     * @throws ClosedException
     */
    public static void close(final AutoCloseable... closes) throws ClosedException {
        List<String> errors = new ArrayList<>();
        boolean errorOccurred = false;
        for (final AutoCloseable c : closes) {
            try {
                if (c != null) {
                    c.close();
                }
            } catch (Exception e) {
                errors.add(e.getMessage());
                errorOccurred = true;
            }
        }
        if (errorOccurred) {
            throw new ClosedException(String.join("\n", errors));
        }
    }
}
